import Schema from 'validate'
const mobileValidate = new Schema({
  mobile: {
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '手机号码不合法'
  }
})
const codeValidate = new Schema({
  code: {
    type: String,
    required: true,
    match: /^\d{6}$/,
    message: '验证码不通过'
  }
})

Page({
  data: {
    countDownVisible: false,
    mobile: "13729206860",
    code: ''
  },
  onLoad({ redirector }) {
    this.redirector = redirector
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async onGetCode() {
    const mobile = this.data.mobile

    const errs = mobileValidate.validate({ mobile: mobile })
    // console.log(4443, errs);
    if (errs.length) {
      return wx.utils.toast(errs[0].message)
    }

    const res = await wx.http({
      url: '/code',
      data: { mobile }
    })
    console.log(res);
    this.setData({
      countDownVisible: true
    })
  },
  async onSubmit() {
    const mobile = this.data.mobile // 转成数字类型
    const code = this.data.code // 转成数字类型
    const errs = mobileValidate.validate({ mobile: mobile })
    // console.log(4443, errs);
    if (errs.length) {
      return wx.utils.toast(errs[0].message)
    }
    const codeErrs = codeValidate.validate({ code: code })
    // console.log(4443, errs);
    if (codeErrs.length) {
      return wx.utils.toast(codeErrs[0].message)
    }
    const res = await wx.http({
      url: '/login',
      method: 'post',
      data: { mobile, code },
    })
    if (res.code !== 10000) return wx.utils.toast(res.message)
    const app = getApp() // 获取到应用实例
    app.setToken(res.data.token, res.data.refreshToken)

    if (this.redirector) {
      wx.reLaunch({ url: '/' + this.redirector })
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  }
})
